package com.example.administrator.social.activitys;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.social.R;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;

import java.util.Iterator;
import java.util.List;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int LOGIN_SUCCESS_SAVE_USER = 0;
    Button mLoginButton,mRegButton;
    EditText mUserNameEdit,mUserPwdEdit;
    private Context mContext;

    private void saveLoginUserInfo(Object obj) {
        String userName = (String) obj;
        //获取编辑器
        SharedPreferences.Editor editor = getSharedPreferences("user", Context.MODE_PRIVATE).edit();
        editor.putString("name", userName);
        editor.commit();//提交修改
        startActivity(new Intent(mContext,MainActivity.class));
        finish();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this;
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                200);
       /*EMOptions options = new EMOptions();
       if(options.getAutoLogin()){
            startActivity(new Intent(mContext, MainActivity.class));
            finish();
        }*/
        mUserNameEdit = (EditText) findViewById(R.id.login_user_name);
        mUserPwdEdit = (EditText) findViewById(R.id.login_user_pwd);
        mLoginButton = (Button) findViewById(R.id.login_button);
        mRegButton = (Button) findViewById(R.id.reg_button);
        mLoginButton.setOnClickListener(this);
        mRegButton.setOnClickListener(this);


    }

    @Override
    protected void onStart() {
        super.onStart();
        //init Platform AS a Service SDK
        initHxSDK();
    }

    private void initHxSDK() {

        /**
         * if have service for third-party
         */
       /* String processAppName = getAppName(pid);
        if (processAppName == null ||!processAppName.equalsIgnoreCase(appContext.getPackageName())) {
            return;
        }*/

        EMOptions options = new EMOptions();
        //Do you need validation when adding friends? default true?
        options.setAcceptInvitationAlways(true);

        //message attachments is upload or download from HX ?
        options.setAutoTransferMessageAttachments(true);
        options.setAutoLogin(true);

        //download the attachments picture
        options.setAutoDownloadThumbnail(true);
        EMClient.getInstance().init(mContext, options);
        EMClient.getInstance().setDebugMode(true);
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.login_button:
                doLogin();
                break;
            case R.id.reg_button:
                doRegUser();
        }
    }


    private void doRegUser() {
        startActivity(new Intent(mContext,RegisterActivity.class));
    }

    private void doLogin() {
        //send Request
        final String userName = mUserNameEdit.getText().toString();
        String password = mUserPwdEdit.getText().toString();
        if(userName.trim().equals("")||password.trim().equals("")){
            Toast.makeText(mContext,R.string.login_error,Toast.LENGTH_SHORT).show();
            return;
        }
        //if you haven't the server for yourself; login for the HX
       EMClient.getInstance().login(userName, password, new EMCallBack() {
            @Override
            public void onSuccess() {
                Message msg = Message.obtain();
                msg.what = LOGIN_SUCCESS_SAVE_USER;
                msg.obj = userName;
                saveLoginUserInfo(userName);
            }

            @Override
            public void onError(int i, String s) {
              runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                      Toast.makeText(mContext,R.string.login_error,Toast.LENGTH_SHORT).show();
                  }
              });
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

       // if you have the server for yourself
        //do login request for yourself server
    }
}
